﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace Elentok.Common.Wpf.Helpers
{
  /// <summary>
  /// Various resource-related methods
  /// </summary>
  public static class ResourceHelper
  {
    /// <summary>
    /// Gets the first matching resource of the type.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="assemblyName">Name of the assembly.</param>
    /// <param name="resourceFilename">The resource filename.</param>
    /// <returns></returns>
    public static T GetResource<T>(string assemblyName, string resourceFilename) where T : class
    {
      return GetResource<T>(assemblyName, resourceFilename, String.Empty);
    }

    /// <summary>
    /// Gets the resource by name
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="assemblyName">Name of the assembly.</param>
    /// <param name="resourceFilename">The resource filename.</param>
    /// <param name="name">The name.</param>
    /// <returns></returns>
    public static T GetResource<T>(string assemblyName, string resourceFilename, string name) where T : class
    {
      if (string.IsNullOrEmpty(assemblyName) || string.IsNullOrEmpty(resourceFilename))
        return default(T);
      string uriPath = string.Format("/{0};component/{1}", assemblyName, resourceFilename);
      Uri uri = new Uri(uriPath, UriKind.Relative);
      return GetResource<T>(uri, name);
    }

    /// <summary>
    /// Gets the resource by name
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="resourceDictionaryUri">The URI of the resource dictionary.</param>
    /// <param name="resourceName">The name of the resource within the dictionary.</param>
    /// <returns></returns>
    public static T GetResource<T>(Uri resourceDictionaryUri, string resourceName) where T : class
    {
      ResourceDictionary resource = Application.LoadComponent(resourceDictionaryUri) as ResourceDictionary;
      if (resource == null)
        return default(T);

      if (!string.IsNullOrEmpty(resourceName))
      {
        if (resource.Contains(resourceName))
          return resource[resourceName] as T;
        return default(T);
      }
      return resource.Values.OfType<T>().FirstOrDefault();
    }
  }
}
